﻿using AutoMapper;
using MD5Hash;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Linq.Dynamic.Core;
using System.Text;
using Yuekao.API.Read.Command;
using Yuekao.Domain.API;
using Yuekao.Domain.BaseReposi;
using Yuekao.Domain.dto;
using Yuekao.Domain.Entitys;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace Yuekao.API.Read.CommandHandler
{
    public class LoginCommandHandler : IRequestHandler<LoginCommand, APIResult<UserDTO>>
    {
        private readonly IBaseRepository<UserModel> userbaseRepository;
        private readonly IBaseRepository<RoleModel> rolebaseRepository;
        private readonly IMapper mapper;
        public LoginCommandHandler(IBaseRepository<RoleModel> rolebaseRepository, IBaseRepository<UserModel> userbaseRepository, IMapper mapper)
        {
            this.rolebaseRepository = rolebaseRepository;
            this.userbaseRepository = userbaseRepository;
            this.mapper = mapper;
        }

        public Task<APIResult<UserDTO>> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            APIResult<UserDTO> result=new APIResult<UserDTO>();

            var list = userbaseRepository.GetValue(x=>x.UserName==request.UserName);
            if (list == null)
            {
                result.Code = APIEnum.Fail;
                result.Message = "用户名不存在";
                return Task.FromResult(result);
            }
            if(list.UserPass!=request.UserPass.GetMD5())
            {
                result.Code = APIEnum.Fail;
                result.Message = "密码不匹配";
                return Task.FromResult(result);
            }

            var res=mapper.Map<UserDTO>(list);
            res.RoleName = rolebaseRepository.GetValue(x=>x.RoleId==res.RoleId).RoleName;
            result.Code = APIEnum.Success;
            result.Message = "登录成功";
            result.Data = res;
            result.Token = CreateTokenString();
            return Task.FromResult(result);
        }
        /// <summary>
        /// 生成 JWT Token（令牌）
        /// </summary>
        /// <returns></returns>
        private string CreateTokenString()
        {
            //私钥
            var secretByte = Encoding.UTF8.GetBytes("kdsfldsflkdslkflkdsflkdslfdslkflk");
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            // 生成Token
            var token = new JwtSecurityToken(
                issuer: "BeiJingBW",
                audience: "BeiJingBW",
                expires: DateTime.Now.AddDays(1), // 一天后过期
                signingCredentials: signingCredentials
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }

    }
}
